package com.jiyiren.bms.aty;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.PersistableBundle;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.Toolbar;
import android.view.MenuItem;
import android.view.View;
import android.widget.Toast;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.amap.api.maps.AMap;
import com.amap.api.maps.CameraUpdateFactory;
import com.amap.api.maps.LocationSource;
import com.amap.api.maps.MapView;
import com.amap.api.maps.UiSettings;
import com.amap.api.maps.model.BitmapDescriptorFactory;
import com.amap.api.maps.model.LatLng;
import com.amap.api.maps.model.Marker;
import com.amap.api.maps.model.MarkerOptions;
import com.jiyiren.bms.R;
import com.jiyiren.bms.utiltool.ShowToast;

public class MapActivity extends BaseCompatActivity implements LocationSource,AMapLocationListener {
//    private App mapp;
    private MapView mMapView = null;
    private AMap mMap;
    private UiSettings mUiSettings;//定义一个UiSettings对象
    //定位监听器，通过地图定位的监听器获得mListener,然后设置位置变动的数据
    private OnLocationChangedListener mListener = null;

    public AMapLocationClient mLocationClient = null;//定位发起
    private AMapLocationClientOption mLocationOption = null;//定位参数
    private Marker marker=null;
    private Bitmap mbitmap=null;
    private boolean isFirstLoc=true;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_map);
//        mapp=App.getAppInstance();
        initToolBar();
        //获取地图控件引用
        mMapView = (MapView) findViewById(R.id.map);
        //在activity执行onCreate时执行mMapView.onCreate(savedInstanceState)，实现地图生命周期管理
        mMapView.onCreate(savedInstanceState);
        if(mMap==null){
            mMap=mMapView.getMap();
        }
        initLocation();
    }

    public void initToolBar(){
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);

        toolbar.setNavigationIcon(R.mipmap.ic_arrow_back);//设置导航栏图标
        toolbar.setNavigationContentDescription(R.string.menu_back);
        toolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                MapActivity.this.finish();
            }
        });
        toolbar.setTitle(R.string.menu_map_title);//设置主标题
        toolbar.setTitleTextColor(ContextCompat.getColor(this,R.color.white));

        toolbar.inflateMenu(R.menu.base_toolbar_menu);//设置右上角的填充菜单

        toolbar.setOnMenuItemClickListener(new Toolbar.OnMenuItemClickListener() {
            @Override
            public boolean onMenuItemClick(MenuItem item) {
                int menuItemId = item.getItemId();
                if (menuItemId == R.id.action_done) {
                    savePosition();
                } else if (menuItemId == R.id.action_standard) {
                    if(mMap!=null&&mMap.getMapType()!=AMap.MAP_TYPE_NORMAL){
                        mMap.setMapType(AMap.MAP_TYPE_NORMAL);
                    }
                    Toast.makeText(MapActivity.this , R.string.item_standard , Toast.LENGTH_SHORT).show();

                } else if (menuItemId == R.id.action_satellite) {
                    if(mMap!=null&&mMap.getMapType()!=AMap.MAP_TYPE_SATELLITE){
                        mMap.setMapType(AMap.MAP_TYPE_SATELLITE);
                    }
                    Toast.makeText(MapActivity.this , R.string.item_satellite , Toast.LENGTH_SHORT).show();
                }else if(menuItemId == R.id.action_night){
                    if(mMap!=null&&mMap.getMapType()!=AMap.MAP_TYPE_NIGHT){
                        mMap.setMapType(AMap.MAP_TYPE_NIGHT);
                    }
                    Toast.makeText(MapActivity.this , R.string.item_night , Toast.LENGTH_SHORT).show();
                }
                return true;
            }
        });
    }

    //保存位置
    public void savePosition(){
        if(marker!=null){
            final LatLng latLng=marker.getPosition();
            String latlngstr=getString(R.string.longitude)+latLng.longitude+"\n"+
                    getString(R.string.latitude)+latLng.latitude;
            AlertDialog.Builder builder=new AlertDialog.Builder(this)
                    .setTitle(R.string.ensure_tips)
                    .setMessage(latlngstr)
                    .setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.dismiss();
                        }
                    })
                    .setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            mapp.setLatLng(latLng);
                            mapp.setToggled(true);
                            mapp.setSimuUserId("0");
                            MapActivity.this.finish();
                        }
                    });
            builder.create();
            builder.show();
        }else{
            ShowToast.show(this,R.string.pelase_choose_one);
        }
    }

    protected ProgressDialog showSpinnerDialog() {
        ProgressDialog dialog = new ProgressDialog(this);
        dialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
        dialog.setCancelable(false);
//        if (!isFinishing()) {
//            dialog.show();
//        }
        return dialog;
    }
    Handler mhandler=new Handler(){
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what){
                case 1:
                    break;
            }
        }
    };
    //初始化地图定位按钮显示
    public void initLocation(){
        mbitmap=BitmapFactory.decodeResource(getResources(),R.mipmap.position);
        mUiSettings = mMap.getUiSettings(); //实例化UiSettings类
        mMap.setLocationSource(this);       // 设置定位监听
        mUiSettings.setMyLocationButtonEnabled(true); // 显示默认的定位按钮
        mMap.setMyLocationEnabled(true);// 可触发定位并显示定位层
        mMap.setOnMapClickListener(new AMap.OnMapClickListener() {
            @Override
            public void onMapClick(LatLng latLng) {
                if(marker!=null) {
                    marker.remove();
                }
                marker=mMap.addMarker(new MarkerOptions().
                        position(latLng).
                        title("Aim").
                        snippet("DefaultSnip").
                        icon(BitmapDescriptorFactory.fromBitmap(mbitmap)));
            }
        });
        initLocate();
    }

    public void initLocate(){
        //初始化定位
        mLocationClient = new AMapLocationClient(getApplicationContext());
        //设置定位回调监听
        mLocationClient.setLocationListener(this);
        //启动定位
        mLocationClient.startLocation();
    }


    //提供外部进入该activity的方法
    public static void enterMapAty(Context context) {
        Intent i = new Intent(context, MapActivity.class);
        context.startActivity(i);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mMapView.onDestroy();
    }

    @Override
    protected void onResume() {
        super.onResume();
        mMapView.onResume();
    }

    @Override
    protected void onPause() {
        super.onPause();
        mMapView.onPause();
    }

    @Override
    public void onSaveInstanceState(Bundle outState, PersistableBundle outPersistentState) {
        super.onSaveInstanceState(outState, outPersistentState);
        mMapView.onSaveInstanceState(outState);
    }

    //LocationSource 激活定位
    @Override
    public void activate(OnLocationChangedListener onLocationChangedListener) {
        mListener=onLocationChangedListener;
    }
    //LocationSource 取消定位
    @Override
    public void deactivate() {
        mListener=null;
    }

    //AMapLocationListener 定位接口
    @Override
    public void onLocationChanged(AMapLocation amapLocation) {
        if (amapLocation != null) {
            if (amapLocation.getErrorCode() == 0) {
                mListener.onLocationChanged(amapLocation);
                if(isFirstLoc) {
                    mMap.moveCamera(CameraUpdateFactory.zoomTo(17));
                    isFirstLoc=false;
                }
            }
        }
    }
}
